package com.portal.rabbitmq.demo.consumer.service;

import com.alibaba.fastjson.JSON;
import com.portal.rabbitmq.demo.constants.MessageConstants;
import com.portal.rabbitmq.demo.consumer.entity.OrderDTO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 电子邮件服务
 *
 * @author Amadeus
 * @date 2021/05/18
 */
@Slf4j
@Service
public class EmailService {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MessageConstants.EXCHANGE_QUEUE, durable = "true"),
            exchange = @Exchange(name = MessageConstants.EXCHANGE_NAME),
            key = MessageConstants.ROUTING_KEY),
            containerFactory = "rabbitListenerContainerFactory")
    public void consumersMessage(Message message, Channel channel) throws IOException {
        log.info("接收到消息：" + JSON.toJSONString(message));
        //消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 消息体
        String msg = new String(message.getBody());
        log.info("消息体：" + msg);
        long deliveryTag = messageProperties.getDeliveryTag();
        OrderDTO orderDTO = JSON.parseObject(msg, OrderDTO.class);
        try {
            //TODO 具体业务处理
            log.info("打印:{}", JSON.toJSONString(orderDTO));

            //手动抛出异常测试
            //throw new Exception("测试异常抛出");

            // 业务处理成功执行ack操作
            // 第一个参数：该条消息的index，
            // 第二个参数：是否批量ack，如果是TRUE，则小于index的消息一次性ack
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            // 业务处理异常，执行nack操作，或者根据实际业务场景处理
            // 第一个参数：该条消息的index，
            // 第二个参数：是否批量ack，如果是TRUE，则小于index的消息一次性拒绝
            // 第三个参数：被拒绝的消息是否重新入队列
            e.printStackTrace();
            log.info("消息处理异常:{}", msg);
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
